const express = require('express')
const Result = require('../models/Result')
const {
  orLike,
  orLimit,
  queryTotal,
  querySqlTotal,
  querySql,
  insert,
  deleteData,
  update,
  queryOne
} = require('../db/index')

const router = express.Router()
// 新增用户
router.post('/addSinger', async (req, res, next) => {
  let result = await insert(`insert into singer values(null, '${req.body.singerName}')`)

  new Result(result, '新增成功').success(res)
})

// 删除用户
router.post('/deleteSinger', async (req, res, next) => {
  await deleteData(`delete from singer where id = ${req.body.id}`)
  new Result(true, '删除成功').success(res)
})

// 修改用户信息
router.post('/updateSinger', async (req, res, next) => {
  let temp = ''
  // sql拼接
  for(let key in req.body) {
    if(req.body[key] && !['id', 'isEdit'].includes(key)) {
      temp += `${key} = '${req.body[key]}',`
    }
  }
  temp = temp.substr(0, temp.length - 1)
  // 修改
  update(`UPDATE singer SET ${temp} WHERE id = ${req.body.id}`)
  new Result(true, '保存成功').success(res)
})

// 获取用户分页列表
router.post('/getSingerPage', async (req, res, next) => {
  let result = await querySql(
    `select * from singer ${orLike(req, 'singerName')} ${orLimit(req)}`
    )
  let total = await querySqlTotal(`select * from singer ${orLike(req, 'singerName')}`)
  new Result({data: result, total}, '查询成功').success(res)
})

module.exports = router
